#!/usr/bin/env python
__author__="simon"
__date__ ="$Feb 13, 2010 1:18:45 PM$"

import sys,os
from multiprocessing import Manager,Process
from multiprocessing import Queue,Pipe
from multiprocessing.connection import Listener
import logging
import socket,multiprocessing
import string


class ServerState():
    def __init__(self,manager):
        self.messages = manager.list()
        self.buddies = manager.list()


class ChatServer():
    def __init__(self,port):
        self.port = port
        self.clientList = []
        address = ('localhost', port)
        self.mainSocket = Listener(address)
        #self.new_conn_pipe,other_end_pipe = Pipe()
        self.manager = Manager()
        self.state = ServerState(self.manager)

        self.listen()

    def listen(self):
        while(1):
            print "waiting for client..."
            conn = self.mainSocket.accept()
            queue = Queue()
            proc = Process(target=self.client,args=(conn,queue,self.state))
            proc.start()
            self.clientList += [(proc,queue,conn)]
            print "connected to client"

    def client(self,conn,queue,state):
        logging.debug("New client process listening")
        print "New client process listening"
        lastIndex = len(state.messages)
        while(1):
            currentIndex = len(state.messages)
            if  currentIndex > lastIndex:
                buffer = state.messages[lastIndex:currentIndex]
                lastIndex = currentIndex
                conn.send(buffer)

            if conn.poll():
                data = conn.recv()
                logging.debug(data)
                state.messages.append(data)
        

if __name__ == "__main__":
    port = 2020
    if len( sys.argv) > 1:
        port = int(sys.argv[1])
    LOG_FILENAME = './main.log'
    logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
    logging.debug("test")
    server = ChatServer(port)
